{% extends "../single_page.html" %}

{% block specific_page_css %}
  <style>
    button.button_group1+div+div {
        width: 200px;
        margin-top: 7px;
        margin-left: 1em;
        z-index: 1000;
    }
  </style>
{% endblock %}

{% block title %}
<title>样本库信息管理 核酸使用记录信息</title>
{% endblock %}

{% block header_title %}
<h1>核酸使用记录信息</h1>
{% endblock %}

{% block header_ol %}
    <li class="breadcrumb-item"><a href="/Home/">Home</a></li>
    <li class="breadcrumb-item">BIS</li>
    <li class="breadcrumb-item active">DNAUsageRecordInfo</li>
{% endblock %}

{% block ModalFormHeader %}
    <p id="ModalFormHeader" class="text-warning front-weight-bold"></p>
{% endblock %}

{% block page-script %}
<script>
  $(document).ready(function () {
      $("#sidebar_BIS>a").addClass("active");
      $("#sidebar_BIS").addClass("menu-open");
      $("#sidebar_BIS>ul>li:eq(3)>a").addClass("active");
      $(".sidebar").removeAttr("hidden");

      let model0 = "DNAUsageRecordInfo";
      let url0 = '/api/BIS/' + model0 + '/';
      let url1 = '/api/BIS/ExtractInfo/';
      let id0 = 0;
      let bulk_update_bool = {% if perms.BIS.bulk_update_DNAUsageRecordInfo %} true {% else %} false {% endif %};
      let bulk_delete_bool = {% if perms.BIS.bulk_delete_DNAUsageRecordInfo %} true {% else %} false {% endif %};

      function update_func(e, id0){
          e.preventDefault();
          // 递交前检查，一般是检测model的外键是否存在
          let data1 = $.ajax({
              url: url1, dataType: 'json', contentType: "application/json",
              type: "get", async: false, data: { dna_id: $('#dna_id').val(),
                  fields: "id,sampleinventoryinfo,failM,researchM,othersM"}
          }).responseJSON[0];
          if (data1 === undefined) {
              $('#myModalError').text('错误！！！核酸提取编号不存在，请填写正确的核酸提取编号。');
              return
          }

          let type = $('#type').val();
          let method = '';
          let url_ajax0 = url0;
          let url_ajax1 = url1 + data1.id + '/';
          let send_data0 = $("#modelForm").find(":not(#dna_id)").serialize() + '&' +
              $.param({ extractinfo: data1.id, sampleinventoryinfo: data1.sampleinventoryinfo });
          let old_data0;
          if (type === 'new') {
              // new
              method = 'POST';
              // POST前检查，一般是检测model的关键字段值是否存在
              data0 = $.ajax({
                  url: url0, dataType: 'json', contentType: "application/json",
                  type: "get", async: false, data: {
                      extractinfo: data1.id, usage_date: $('#usage_date').val(),
                      usage: $('#usage').val(), fields: "id"
                  }
              }).responseJSON[0];
              if (data0 !== undefined) {
                  $('#myModalError').text('错误！！！该条核酸使用记录已存在，无法添加。如需更新该条目，请在对应行进行更新操作。');
                  return
              }
          } else {
              // edit
              url_ajax0 = url0 + id0 + '/';
              method = 'PUT';
              old_data0 = $.ajax({
                  url: url_ajax0, dataType: 'json', contentType: "application/json",
                  type: "get", async: false, data: { fields: "id,dna_id,usage,mass,singleLB_id" }
              }).responseJSON;
          }

          $.ajax({
              url: url_ajax0,
              method: method,
              data: send_data0,
              headers: {'X-HTTP-Method-Override': 'PATCH'},
              success: function () {
                  let v_tmp = $('#dna_id').val();
                  let filter1 = $('#usage').val();
                  if (type === 'new') {
                      databaseRecordAjaxPut('{{ user.id }}', model0, "单项添加", "核酸提取编号：" + v_tmp);
                      $('#myModalError').text('添加成功！！！核酸提取编号：' + v_tmp);
                      // 记录样本提取表条目变化
                      if (filter1 === '建库失败') {
                          data1.failM = parseFloat(data1.failM) + parseFloat($('#mass').val());
                      } else if (filter1 === '科研项目') {
                          data1.failM = parseFloat(data1.researchM) + parseFloat($('#mass').val());
                      } else if (filter1 === '其他') {
                          data1.failM = parseFloat(data1.othersM) + parseFloat($('#mass').val());
                      }
                  } else {
                      databaseRecordAjaxPut('{{ user.id }}', model0, "单项更新", "核酸提取编号：" + v_tmp);
                      $('#myModalError').text('更新成功！！！核酸提取编号：' + v_tmp);
                      // 记录样本提取表条目变化
                      if (filter1 === '建库失败') {
                          data1.failM = parseFloat(data1.failM) + parseFloat($('#mass').val()) - parseFloat(old_data0.mass);
                      } else if (filter1 === '科研项目') {
                          data1.failM = parseFloat(data1.researchM) + parseFloat($('#mass').val()) - parseFloat(old_data0.mass);
                      } else if (filter1 === '其他') {
                          data1.failM = parseFloat(data1.othersM) + parseFloat($('#mass').val()) - parseFloat(old_data0.mass);
                      }
                  }
                  // 更新样本提取表
                  console.info(">>>>> data1", data1);
                  console.info(">>>>> url_ajax1", url_ajax1);
                  $.ajax({
                      url: url_ajax1,
                      method: 'PATCH',
                      data: $.param({
                          failM: data1.failM, researchM: data1.researchM, othersM: data1.othersM
                      }),
                      headers: {'X-HTTP-Method-Override': 'PATCH'},
                      success: function () {
                          databaseRecordAjaxPut('{{ user.id }}', "ExtractInfo", "单项更新", "核酸提取编号：" + v_tmp);
                      },
                      error: function (jqXHR, textStatus, errorThrown) {
                          console.info(jqXHR , textStatus , errorThrown)
                      }
                  });

                  setTimeout(
                      function () {
                          window.location.reload(true);
                      }, 3000
                  );
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  $('#myModalError').text('出现错误！！！请联系管理员');
                  console.info(url_ajax0, method, send_data0);
                  console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
              }
          });
      }

      function delete_by_id (id_func){
          let url_ajax0 = url0 + id_func + '/';
          let old_data0 = $.ajax({
              url: url_ajax0, dataType: 'json', contentType: "application/json",
              type: "get", async: false, data: { fields: "id,dna_id,usage,mass,singleLB_id"}
          }).responseJSON;
          let res = [];
          $.ajax({
              url: url_ajax0,
              method: 'DELETE',
              success: function () {
                  res.push("success");
                  res.push(id_func);
                  // 更新样本提取表
                  let data1 = $.ajax({
                      url: url1, dataType: 'json', contentType: "application/json",
                      type: "get", async: false, data: { dna_id: old_data0.dna_id, fields: "id,failM,researchM,othersM" }
                  }).responseJSON[0];
                  if (old_data0.usage === '建库失败') {
                      data1.failM = parseFloat(data1.failM) - parseFloat(old_data0.mass);
                  } else if (old_data0.usage === '科研项目') {
                      data1.researchM = parseFloat(data1.researchM) - parseFloat(old_data0.mass);
                  } else if (old_data0.usage === '其他') {
                      data1.othersM = parseFloat(data1.othersM) - parseFloat(old_data0.mass);
                  }
                  $.ajax({
                      url: url1 + data1.id + '/',
                      method: 'PATCH',
                      data: $.param({
                          failM: data1.failM, researchM: data1.researchM, othersM: data1.othersM
                      }),
                      headers: {'X-HTTP-Method-Override': 'PATCH'},
                      success: function () {
                          res.push("success");
                          res.push(data1.id);
                      },
                      error: function (jqXHR, textStatus, errorThrown) {
                          res.push("error");
                          res.push(jqXHR + ';' + textStatus + ';' + errorThrown)
                      }
                  });
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  res.push("error");
                  res.push(jqXHR + ';' + textStatus + ';' + errorThrown);
                  res.push("error");
                  res.push(jqXHR + ';' + textStatus + ';' + errorThrown);
              }
          });
          return res;
      }

      function delete_func(model0, url0, id0){
          let res = delete_by_id(id0);
          if (res[2] === "success") {
              databaseRecordAjaxPut('{{ user.id }}', "ExtractInfo", "单项更新", "id：" + res[3]);
          } else {
              console.log(res[3]);
          }
          if (res[0] === "success") {
              databaseRecordAjaxPut('{{ user.id }}', model0, "单项删除", "id：" + res[1]);
              window.location.reload(true);
          } else {
              console.log(res[1]);
          }
      }

      function bulkDelete_func(table, model0, url0){
          let arrayLen = table.rows(".selected").data().length;
          if (arrayLen > 0) {
                let id_list0 = [];
                let id_list1 = [];
                for (let i = 0; i < arrayLen; i++) {
                    let delete_id = table.rows(".selected").data()[i]['id'];
                    let res = delete_by_id(delete_id);
                    if (res[0] === "success") {
                        id_list0.push(res[1]);
                    }
                    if (res[2] === "success") {
                        id_list1.push(res[3]);
                    }
                }
                databaseRecordAjaxPut('{{ user.id }}', model0, "批量删除", "id_list：[" + id_list0 + "]");
                databaseRecordAjaxPut('{{ user.id }}', "ExtractInfo", "批量更新", "id_list：[" + id_list1 + "]");
                window.location.reload(true);
            } else {
                $('#bulkDelError').text('没有行被选中，请先选中目标行。');
            }
      }

      function action_afterTableInit(table_init){
          table_init.rows().every(function (rowIdx, tableLoop, rowLoop) {
              let row_data = this.data;
              if (row_data.usage === "建库成功"){
                  let rm_cell = table.cell(rowIdx, 10).node;
                  $(rm_cell).empty();
              }
          });
      }

      let input_params = {
          "title1_text": "核酸使用记录信息 总条目数： ",
          "fields": [
              //                    [   0,     1,      2,               3,        4,       5,       6  ]
              // input类型是select： [ field, name, 是否出现在modal, modal中排序, 是否必填, input类型, [[value, text]] ]
              // input类型不是select： [ field, name, 是否出现在modal, modal中排序, 是否必填, input类型, value ]
              ["dna_id", "核酸提取编号", 1, 0, 1, "text"],
              ["sampler_id", "华大编号", 0],
              ["usage_date", "使用日期", 1, 1, 1, "date"],
              ["mass", "使用量(ng)", 1, 2, 1, "number_0.001"],
              ["usage", "用途", 1, 3, 1, "select", [["建库失败", "建库失败"], ["科研项目", "科研项目"],["其他", "其他"]]],
              ["singleLB_id", "建库编号(如有)", 1, 4, 0, "text", "无"],
              ["memo", "备注", 1, 5, 0, "text", "无"],
              ["last_modify_time", "上次修改时间", 0],
              ["create_time", "创建时间", 0]
          ],
          "action_afterTableInit": action_afterTableInit,
          "update_func": update_func,
          "delete_func": delete_func,
          "bulkDelete_func": bulkDelete_func,
          "download_excel": '/ADVANCE/download_excel/BIS_' + model0 + '/',
          "ModalFormHeader_p": '只能添加 非“建库成功” 的记录，如需添加 “建库成功” 记录，请转到不同实验项目中的样本建库信息页面'
      };
      single_page_generator(model0, url0, id0, bulk_update_bool, bulk_delete_bool, input_params);

  });
</script>
{% endblock %}
